<?php
/*
* 本类封装修改后台icare_main的操作;
* 所有操作尽量封装, 为以后对前端透明调用做铺垫;
*
* author: hikerwu
* date:2012-09-10
*/

class DBTools
{
    public $_info = array();
    private static $_obj = null;
    static function getInstance()
    {
        if( !self::$_obj )
        {
            self::$_obj = new self();
        }

        return self::$_obj;
    }

    /**
     * 更新数据库;如update语句;不返回数据的查询;
     *
     * @$param,string,数据库类型,
            如:MAIN_R
     * @$param,string,完整的sql语句,
            如:select * from table
     * @$return,array(
            'err'=>'', 错误信息;
            'ret'=>'', 是否执行成功;
            );
     */
    function update( $dbType, $sql )
    {
        $retinfo = array('err'=>'', 'ret'=>'');
        $mysql_conn = ClientFactory::getMysqlClient( $dbType, 0 ) ;
        if( $mysql_conn == null )
        {
            $err = ClientFactory::getError() ;
            $retinfo['err'] = "connect db faild, error=[{$err}]";
            $retinfo['ret'] = false;
            return $retinfo;
        }

        if( !($rs = mysql_query( $sql, $mysql_conn )) )
        {
            $retinfo['err'] = "mysql_query faild, error=[" . mysql_error() . "]";
            $retinfo['sql'] = $sql;
            $retinfo['ret'] = false;
            return $retinfo;
        }

        $num = mysql_affected_rows();
        $retinfo['num'] = $num;
        $retinfo['ret'] = true;
        return $retinfo;
    }

    /**
     * 获取数据;如select语句;返回查询到的数据;
     *
     * @$param,string,数据库类型,
            如:MAIN_R
     * @$param,string,完整的sql语句,
            如:select * from table
     * @$param,array,返回的数据,
            底层接口返回的数据结构, 行记录的数组;
     * @$return,array(
            'err'=>'', 错误信息;
            'ret'=>'', 是否执行成功;
            );
     */
    function select( $dbType, $sql, &$results )
    {
        $retinfo = array('err'=>'', 'ret'=>'');
        $mysql_conn = ClientFactory::getMysqlClient( $dbType, 0 ) ;
        if( $mysql_conn == null )
        {
            $err = ClientFactory::getError() ;
            $retinfo['err'] = "connect db faild, error=[{$err}]";
            $retinfo['ret'] = false;
            return $retinfo;
        }

        $rs = mysql_query( $sql, $mysql_conn );
        if( $rs === false )
        {
            $retinfo['err'] = "mysql_query faild, error=[" . mysql_error() . "]";
            $retinfo['sql'] = $sql;
            $retinfo['ret'] = false;
            return $retinfo;
        }

        while ($row=mysql_fetch_array($rs))
        {
            $results[] = $row;
        }          
        mysql_free_result($rs); 


        $retinfo['ret'] = true;
        return $retinfo;
    }
    

    /**
     * 获取黑名单列表;
     *
     * @$param,string,数据库类型,
            如:MAIN_R
     * @$param,array,返回的数据,
            底层接口返回的数据结构, 行记录的数组;
     * @$param,int,黑名单的类型
            如:0=id, 1=url
     * @$return,
     */
    function getBlackList( $dbType, &$results, $type )
    {
        $type = (int)$type;
        
        $tblName = "t_blacklist";
        if( !$this->_time ) $this->_time = time();
        $etime = $this->_time - 90*86400;//最早时间
        $sql = "select id_url from {$tblName} where {$type}=type and {$etime}<time";

        $retinfo = $this->select( $dbType, $sql, &$results );
        return $retinfo;
    }

    /**
     * Add by kimhuang 2012-09-18
     * get key words from table t_news_content by id
     */
    function getKeyWordsById($id)
    {
        $retinfo = array('err' => '', 'ret' => true, 'value' => '');
        if (!$id) {
            $retinfo['ret'] = false;
            $retinfo['err'] = 'id is null';
        }

        $mysql_conn = ClientFactory::getMysqlClient( 'MAIN_R', 0 ) ;
        if( $mysql_conn == null )
        {
            $err = ClientFactory::getError() ;
            $retinfo['err'] = "connect db faild, error=[{$err}]";
            $retinfo['ret'] = false;
            return $retinfo;
        }

        $tblName = 't_news_content';
        $sql = "select key_words from {$tblName} where id='{$id}'";
        $rs = mysql_query( $sql, $mysql_conn );
        if( $rs == false )
        {
            $retinfo['err'] = "mysql_query faild, error=[" . mysql_error() . "]";
            $retinfo['ret'] = false;
            return $retinfo;
        }
        $rd = mysql_fetch_assoc($rs);
        if ($rd != false) {
            $retinfo['value'] = $rd['key_words'];
        }
        return $retinfo;
    }
    
    /**
    * 获取文章的热度值;
    * 
    * @$param,string,文章id;
        如: n_234lj539453l4345jk
    * @$return,
    * Alter by kimhuang 2012-09-23
    */
    function getNewsHot( $id )
    {
        $retinfo = array('err' => '', 'ret' => true, 'value' => '');
        $retinfo['value'] = 0;

        if (!$id) {
            $retinfo = array('err' => 'Param error', 'ret' => false, 'value' => '');
            return $retinfo;
        }
        
        $tblName = 't_news_content';
        $sql = "select hot,time from {$tblName} where id='{$id}'";
        $results = array();
        $retinfo2 = $this->select('MAIN_R', $sql, $results);
        if( $retinfo2['ret'] && $results[0] )
        {
            $retinfo['hot'] = $results[0]['hot'];
            $retinfo['time'] = $results[0]['time'];
        }
        else
        {
            return $retinfo2;
        }

        return $retinfo;
    }
    
    /**
    * 获取文章操作次数值;
    * 
    * @$param,int,文章id;
        如: n_234lj539453l4345jk
    * @$param,number,返回操作次数值;
        e.g. 12.3
    * @$return,;
    */
    function getOperNum( $ids, &$num )
    {
        $redis = redis_tool::getInstance("tj.IcareCntInfo.redis.com");
        $num = $redis->gets($ids);
        return true;
    }
    
    /**
    * 设置文章的初始热度值;并且设置的这个热度值只用于判断是否是新文章, 不做更新;
    * 
    * @$param,string,文章id;
        如: n_234lj539453l4345jk
    * @$param,number,热度值;
        e.g. 12.3
    * @$return,
    */
    function setNewsHotValue($id, $hot)
    {
        $tblName = "t_news_content";
        $sql = "update {$tblName} set hot='{$hot}' where id='{$id}'";
        $retinfo = $this->update( 'MAIN', $sql );
        
        return $retinfo;
    }

    /**
    * 使用单引号包裹字符串;这里还没有做单引号的转义;
    * 
    * @$param,array,需要修改的行;
        如: array('chlid,'chlname'.....
    * @$param,array,修改的终值;
        e.g. array('chlid'=>'new_it','chlname'=>'频道',.....
    * @$param,bool,是否带上列名称,用于更新;
    * @$return,
    */
    function getFields( $keys, $values, $bkey = false)
    {
        $fields = array();
        foreach( $keys as $key )
        {
            if( isset( $values[$key] ) )
            {
                if( $bkey )
                {
                    $fields[] = "`{$key}`='".$values[$key]."'";
                }
                else
                {
                    $fields[] = "'".$values[$key]."'"; 
                }
            }
        }

        if( !$fields )
        {
            throw new Exception("can't find your field in keys[".print_r($keys)
                        ."] from values[".print_r($values)
                        ."].");
        }

        return $fields;
    }

    /**
    * 将字段用符号包裹;
    * 
    * @$param,array,字符串数组;不能是多维数组;
    * @$param,string,包裹的符号;
    * @$return,
    */
    function roundWith( &$arr , $flag )
    {
        if( $arr ) foreach( $arr as &$one )
        {
            if( is_array( $one ) )
            {
                throw new Excption("you should use string of arr[".print_r($arr)
                     ."]");
            }
            $one = $flag.$one.$flag;
        }
    }

    /**
    * 将字段用符号包裹;
    * 
    * @$param,string,读库或者写库;
    * @$param,string,表名称;
    * @$param,array,需要修改的行;
        如: array('chlid,'chlname'.....
    * @$param,array,修改的终值;
        e.g. array('chlid'=>'new_it','chlname'=>'频道',.....
    * @$return,
    */
    function insert( $dbType, $table, $keys, $values )
    {
        $retinfo = array('err'=>'', 'ret'=>'');
        $fields = $this->getFields( $keys, $values, 0 );
        $mysql_conn = ClientFactory::getMysqlClient( $dbType, 0 ) ;
        if( $mysql_conn == null )
        {
            $err = ClientFactory::getError() ;
            $retinfo['err'] = "connect db faild, error=[{$err}]";
            $retinfo['ret'] = false;
            return $retinfo;
        }

        $sql = '';
        $this->roundWith( $keys, '`' );
        $sql = "insert into `{$table}` (".implode($keys, ',').")"
                ." values(".implode($fields, ',').")";
        $this->_info['sql'] = $sql;

        $rs = mysql_query( $sql, $mysql_conn );
        if( $rs === false )
        {
            $retinfo['err'] = "mysql_query faild, error=[" . mysql_error() . "]";
            $retinfo['sql'] = $sql;
            $retinfo['ret'] = false;
            return $retinfo;
        } 

        $num = mysql_affected_rows();
        $retinfo['num'] = $num; 
        $retinfo['ret'] = true;
        return $retinfo;
    }
}

if($argv[0] == basename(__FILE__))
{
    define('BASE_PATH', dirname(dirname(realpath(dirname(__FILE__) ) ) ) );
    define('LOGS_PATH', '/data/icarelogs/server/cache_tools/logs');
    set_include_path(BASE_PATH . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR . get_include_path());

    require_once BASE_PATH.'/library/Base/iniConfig.php' ;
    require_once BASE_PATH."/library/Base/Logs.php" ;
    require_once BASE_PATH."/library/Base/ClientFactory.php" ;
    require_once BASE_PATH."/library/Base/ToolDebug.php" ;


    // 初始化LOG。
    Logs::setFileLogName( "test_db_" ) ;
    ClientFactory::init( 'icare', BASE_PATH . '/../../etc/' ) ;
    
    $obj = DBTools::getInstance();
    /*
    $table = 't_test';
    $keys = array( 'name' );
    $values = array( 'name' => 'hikerwu', 'desc' => 'wu' );
    $r = $obj->insert('MAIN', $table, $keys, $values);
    var_dump($obj->_info, $r);
    //*/
    $str = file_get_contents('../../info_ids.txt');
    $ids = unserialize($str);
    $num = array();
    print_r($ids);
    $obj->getOperNum($ids, $num);
    print_r($num);
}
